package com.zhongjinkang.rhythm.AppView.Activity

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.WindowCompat
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.zhongjinkang.rhythm.AppView.Dialog.LoadingDialog
import com.zhongjinkang.rhythm.viewModel.PublicViewModel

abstract class BaseActivity<VM : ViewModel, VB : ViewBinding>(
    private val viewModelClass: Class<VM>?,
    private val inflate: (LayoutInflater) -> VB,
) : AppCompatActivity() {

    protected lateinit var binding: VB


    protected val loadingDialog by lazy {
        LoadingDialog()
    }
    protected val viewModel by lazy {
        val viewModelProvider = ViewModelProvider(this)
        viewModelClass?.let {
            viewModelProvider[it]
        }


    }

    override fun onCreate(savedInstanceState: Bundle?) {
        WindowCompat.setDecorFitsSystemWindows(window, false)

        super.onCreate(savedInstanceState)
        binding = inflate(layoutInflater)
        setContentView(binding.root)

        PublicViewModel.tokenState.observe(this) {
            if ((PublicViewModel.TokenState.INVALID == it) and (PublicViewModel.isLoginEd.value == true)) {
                startActivity(Intent(this, LoginActivity::class.java))
                finish()
            }

        }

        PublicViewModel.loadingState.observe(this) {
            if (it == PublicViewModel.LoadingState.LOAD_SHOW) {
                loadingDialog.show(supportFragmentManager)
                PublicViewModel.loadingState.value= PublicViewModel.LoadingState.LOADING
            } else if (it == PublicViewModel.LoadingState.LOAD_HIDE) {
                loadingDialog.dismissAllowingStateLoss()
                PublicViewModel.loadingState.value= PublicViewModel.LoadingState.IDEAL

            }
        }

        toRefreshUI(viewModel)
    }



    abstract fun toRefreshUI(viedModel: VM?)





    override fun onDestroy() {
        super.onDestroy()
        if (PublicViewModel.loadingState.value == PublicViewModel.LoadingState.LOADING) {
            loadingDialog.dismissAllowingStateLoss()
            PublicViewModel.loadingState.value= PublicViewModel.LoadingState.IDEAL
        }
    }


}